python爬虫之resquest.get(url,headers=headers)乱码问题 |
您所在的位置:网站首页 › python headers=headers › python爬虫之resquest.get(url,headers=headers)乱码问题 |
今天在尝试爬取百度新闻网标题的时候,出现了爬取的html乱码问题. 爬虫代码如下: import re import requests url='http://news.baidu.com/' headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0' } #response.text 不太准确 转码 是靠推测 data = requests.get(url,headers= headers).content.decode('utf-8') with open('02-news.html','w') as f: f.write(data)在网上找了一堆之后发现代码都是他们说的那样解决 但是乱码还是存在. 后来我把.decode(‘utf-8’)去掉,再在写文件的方式改成’wb’发现问题竟然解决了(但是也没搞懂原因是啥) 修改后的代码: import re import requests url='http://news.baidu.com/' headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0' } #response.text 不太准确 转码 是靠推测 data = requests.get(url,headers= headers).content with open('02-news.html','wb') as f: f.write(data) |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |